<template>
  <el-form class="loginForm" ref="loginFormRef" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px">
    <el-form-item prop="userName">
      <el-input class="el_input" v-model="loginForm.userName" type="text" auto-complete="off" placeholder="账号">
        <template #prepend><Icon class="iconClass" icon="Avatar"></Icon></template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input class="el_input" v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码">
        <template #prepend><Icon class="iconClass" icon="Lock"></Icon></template>
      </el-input>
    </el-form-item>
    <el-form-item class="form_item1">
      <el-checkbox v-model="remberMe" label="记住密码" size="large" />
    </el-form-item>
    <el-form-item style="width: 100%">
      <el-button v-loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
        <span v-if="!loading">登 录</span>
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import type { RouteRecordRaw } from "vue-router";
defineProps(["pageloading"]);
const emit = defineEmits(["update:modelValue"]);
const store = useAllStore();
const loading = ref(false);
const loginFormRef = ref();
const router = useRouter();
const remberMe = ref(true);
let loginForm = reactive({ userName: "", password: "" });
const loginRules = {
  userName: [{ required: true, trigger: "blur", message: "用户名不能为空" }],
  password: [{ required: true, trigger: "blur", message: "密码不能为空" }]
};

interface IPOuserinfo {
  data: {
    token: string;
    user: { userName: string; avatar: string; id: number };
  };
  statusCode: number;
}
function handleLogin() {
  loginFormRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      console.log("error submit!");
      return false;
    }
    let res = await hfoRequest.post<IPOuserinfo>(
      {
        url: "/auth/signIn",
        data: loginForm
      },
      { noToken: true }
    );
    if (res.statusCode != 200) return;
    store.user = res.data.user;
    store.token = `Bearer ${res.data.token}`;
    remberMe.value
      ? (store.account = {
          userName: loginForm.userName,
          password: loginForm.password
        })
      : (store.account = {});
    router.push("/");
  });
}
if (store.account) {
  loginForm = Object.assign(loginForm, store.account);
  remberMe.value = true;
}
onMounted(async () => {
  emit("update:modelValue", false);
});
</script>

<style scoped lang="scss">
.loginForm {
  .form_item1 {
    margin-bottom: 0;
  }
  .el_input {
    height: 0.38rem;
    min-height: 30px;
    input {
      height: 0.38rem;
    }
  }
  .input-icon {
    height: 0.39rem;
    width: 0.14rem;
    margin-left: 0.02rem;
  }
}
</style>
